<?php
require_once '../models/Order.php';
require_once '../utils/Response.php';

class OrderController {
    private $order;

    public function __construct() {
        $this->order = new Order();
    }

    // 创建订单
    public function create() {
        try {
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data) {
                Response::error('无效的请求数据');
            }

            // 验证必需字段
            if (!isset($data['table_number']) || !isset($data['items']) || !is_array($data['items'])) {
                Response::error('缺少必需字段: table_number 或 items');
            }

            // 计算金额
            $total_amount = 0;
            foreach ($data['items'] as $item) {
                $total_amount += $item['price'] * $item['quantity'];
            }
            $tax_amount = $total_amount * 0.08875; // 8.875% 税率
            $grand_total = $total_amount + $tax_amount;

            $this->order->table_number = $data['table_number'];
            $this->order->customer_name = $data['customer_name'] ?? '';
            $this->order->customer_phone = $data['customer_phone'] ?? '';
            $this->order->items = $data['items'];
            $this->order->total_amount = round($total_amount, 2);
            $this->order->tax_amount = round($tax_amount, 2);
            $this->order->grand_total = round($grand_total, 2);
            $this->order->status = 'pending';

            $order_id = $this->order->create();

            if ($order_id) {
                // 获取创建的订单详情
                $created_order = $this->order->getById($order_id);
                Response::success($created_order, '订单创建成功');
            } else {
                Response::error('订单创建失败');
            }
        } catch (Exception $e) {
            Response::error('创建订单失败: ' . $e->getMessage());
        }
    }

    // 获取所有订单
    public function getAll() {
        try {
            $orders = $this->order->getAll();
            Response::success($orders, '订单列表获取成功');
        } catch (Exception $e) {
            Response::error('获取订单列表失败: ' . $e->getMessage());
        }
    }

    // 按状态获取订单
    public function getByStatus() {
        try {
            if (!isset($_GET['status'])) {
                Response::error('请提供状态参数');
            }

            $status = $_GET['status'];
            $orders = $this->order->getByStatus($status);
            Response::success($orders, '订单获取成功');
        } catch (Exception $e) {
            Response::error('获取订单失败: ' . $e->getMessage());
        }
    }

    // 获取订单详情
    public function getDetail() {
        try {
            if (!isset($_GET['id'])) {
                Response::error('请提供订单ID');
            }

            $id = $_GET['id'];
            $order = $this->order->getById($id);

            if (!$order) {
                Response::notFound('订单不存在');
            }

            Response::success($order, '订单详情获取成功');
        } catch (Exception $e) {
            Response::error('获取订单详情失败: ' . $e->getMessage());
        }
    }

    // 按订单号获取订单
    public function getByOrderNumber() {
        try {
            if (!isset($_GET['order_number'])) {
                Response::error('请提供订单号');
            }

            $order_number = $_GET['order_number'];
            $order = $this->order->getByOrderNumber($order_number);

            if (!$order) {
                Response::notFound('订单不存在');
            }

            Response::success($order, '订单获取成功');
        } catch (Exception $e) {
            Response::error('获取订单失败: ' . $e->getMessage());
        }
    }

    // 更新订单状态
    public function updateStatus() {
        try {
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data || !isset($data['id']) || !isset($data['status'])) {
                Response::error('无效的请求数据');
            }

            $id = $data['id'];
            $status = $data['status'];

            // 验证状态值
            $valid_statuses = ['pending', 'preparing', 'ready', 'completed', 'cancelled'];
            if (!in_array($status, $valid_statuses)) {
                Response::error('无效的状态值');
            }

            if ($this->order->updateStatus($id, $status)) {
                $updated_order = $this->order->getById($id);
                Response::success($updated_order, '订单状态更新成功');
            } else {
                Response::error('订单状态更新失败');
            }
        } catch (Exception $e) {
            Response::error('更新订单状态失败: ' . $e->getMessage());
        }
    }

    // 删除订单
    public function delete() {
        try {
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data || !isset($data['id'])) {
                Response::error('无效的请求数据');
            }

            $id = $data['id'];

            if ($this->order->delete($id)) {
                Response::success(null, '订单删除成功');
            } else {
                Response::error('订单删除失败');
            }
        } catch (Exception $e) {
            Response::error('删除订单失败: ' . $e->getMessage());
        }
    }

    // 获取今日统计
    public function getTodayStats() {
        try {
            $stats = $this->order->getTodayStats();
            Response::success($stats, '今日统计获取成功');
        } catch (Exception $e) {
            Response::error('获取今日统计失败: ' . $e->getMessage());
        }
    }

    // 按桌号获取订单
    public function getByTableNumber() {
        try {
            if (!isset($_GET['table_number'])) {
                Response::error('请提供桌号');
            }

            $table_number = $_GET['table_number'];
            $orders = $this->order->getByTableNumber($table_number);
            Response::success($orders, '桌号订单获取成功');
        } catch (Exception $e) {
            Response::error('获取桌号订单失败: ' . $e->getMessage());
        }
    }
}

// 路由处理
$controller = new OrderController();
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if (isset($_GET['id'])) {
            $controller->getDetail();
        } elseif (isset($_GET['order_number'])) {
            $controller->getByOrderNumber();
        } elseif (isset($_GET['status'])) {
            $controller->getByStatus();
        } elseif (isset($_GET['table_number'])) {
            $controller->getByTableNumber();
        } elseif (isset($_GET['stats'])) {
            $controller->getTodayStats();
        } else {
            $controller->getAll();
        }
        break;
    
    case 'POST':
        $controller->create();
        break;
    
    case 'PUT':
        $controller->updateStatus();
        break;
    
    case 'DELETE':
        $controller->delete();
        break;
    
    default:
        Response::error('不支持的请求方法', 405);
}
?>